<?php

namespace App\Console\Commands;

use App\Http\Controllers\Open\XgController;
use App\Models\Administrator;
use App\Models\Content;
use App\Models\Role;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class XgBindKeywords extends Command
{
    protected $signature = 'xg:bindkeywords';

    protected $description = '将关键词绑定到对应的site_id';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        self::bindKeywords();
        echo '\r\n\r\n分配工作执行完成!!!';
    }

    private static function bindKeywords(){

        $keywordDB = DB::table('xg_searchkeyword');

        $keywordCount = $keywordDB->where(['site_id'=>0])->count();
        $siteCount = DB::table('xg_site')->where(['is_stop'=>0])->count();

        $quotient = floor($keywordCount / $siteCount);

        if ($quotient<=1 && $quotient<$siteCount) {
            throw new \Exception("分配量合计小于网站数，不能分配");
        }

        $keyLists = DB::table('xg_searchkeyword')->where(['site_id'=>0])->select()->get()->toArray();

        $siteLists = DB::table('xg_site')->where(['is_stop'=>0])->select()->get()->toArray();

        $chunks = array_chunk($keyLists, $siteCount);

        foreach ($chunks as $k=>$vv) {
            foreach ($vv as $kk=>$v3) {
                $site_id = $siteLists[$kk]->id;
                DB::table('xg_searchkeyword')->where('id',$v3->id)->update(['site_id'=>$site_id,'created_time'=>date("Y-m-d H:i:s")]);
                echo "\n\r{$site_id} ==> ".$v3->searchkeyword;
            }

        }

    }


}
